package com.yk.system.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yk.api.system.dto.CardAlarmDTO;
import com.yk.common.core.domain.BasePageQuery;
import com.yk.common.core.domain.PageResult;
import com.yk.common.core.domain.Result;
import com.yk.common.core.utils.LoginHelper;
import com.yk.system.convert.CardAlarmConvert;
import com.yk.system.entity.CardAlarm;
import com.yk.system.entity.Gateway;
import com.yk.system.service.CardAlarmService;
import com.yk.system.service.GatewayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * 流量卡报警信息记录
 *
 * @author lmx
 * @since 2024-02-21
 */
@Api(tags = "流量卡信息表")
@RestController
@RequestMapping("/cardAlarm")
@RequiredArgsConstructor
public class CardAlarmController {

    private final CardAlarmService cardAlarmService;
    private final GatewayService gatewayService;
    private final CardAlarmConvert cardAlarmConvert;

    @GetMapping("/getById/{id}")
    @ApiOperation("流量卡报警信息记录-查询单个")
    public Result<CardAlarm> getById(@PathVariable(value = "id") Long id) {
        return Result.data(cardAlarmService.getById(id));
    }

    @PostMapping("/save")
    @ApiOperation("流量卡报警信息记录-新增")
    public Result<Boolean> save(@RequestBody @Validated CardAlarmDTO dto) {
        return Result.data(cardAlarmService.save(cardAlarmConvert.dto2Entity(dto)));
    }

    @PostMapping("/update")
    @ApiOperation("流量卡报警信息记录-修改")
    public Result<Boolean> updateById(@RequestBody @Validated CardAlarmDTO dto) {
        return Result.data(cardAlarmService.updateById(cardAlarmConvert.dto2Entity(dto)));
    }

    @GetMapping("/deleteById/{id}")
    @ApiOperation("流量卡报警信息记录-删除")
    public Result<Boolean> deleteById(@PathVariable(value = "id") Long id) {
        return Result.data(cardAlarmService.removeById(id));
    }

    @PostMapping("/list")
    @ApiOperation("流量卡报警信息记录-查询列表")
    public Result<List<CardAlarm>> list(@RequestBody CardAlarmDTO param) {
        final LambdaQueryWrapper<CardAlarm> lambda = new QueryWrapper<CardAlarm>().lambda();
        this.buildCondition(lambda, param);
        return Result.data(cardAlarmService.list(lambda));
    }

    @PostMapping("/page")
    @ApiOperation("流量卡报警信息记录-分页查询")
    public PageResult<CardAlarmDTO> page(@RequestBody BasePageQuery<CardAlarmDTO> pageParam) {
        Long userId = LoginHelper.getLoginUserId();
        List<Gateway> list = gatewayService.list(new LambdaQueryWrapper<Gateway>().eq(Gateway::getCreatedBy, userId));
        if (CollUtil.isEmpty(list)) {
            return PageResult.success(CollUtil.newArrayList(), 0);
        }
        List<String> ccIdList = list.stream().map(Gateway::getCardNumber).collect(Collectors.toList());
        final CardAlarmDTO param = pageParam.getParam();
        final LambdaQueryWrapper<CardAlarm> lambda = new QueryWrapper<CardAlarm>().lambda();
        lambda.in(CardAlarm::getCardno, ccIdList);
        this.buildCondition(lambda, param);
        final IPage<CardAlarmDTO> page = cardAlarmService
                .page(new Page<>(pageParam.getPageNum(), pageParam.getPageSize()), lambda)
                .convert(cardAlarmConvert::entity2Dto);
        if (CollUtil.isNotEmpty(page.getRecords())) {
            page.getRecords().forEach(it -> {
                String cardno = it.getCardno();
                LambdaQueryWrapper<Gateway> gateLambda = new LambdaQueryWrapper<>();
                gateLambda.eq(Gateway::getCardNumber, cardno);
                gateLambda.eq(Gateway::getCreatedBy, userId);
                List<Gateway> gatewayList = gatewayService.list(gateLambda);
                if (CollUtil.isNotEmpty(gatewayList)) {
                    List<String> nameList = gatewayList.stream().map(Gateway::getName).collect(Collectors.toList());
                    String gateName = String.join(",", nameList);
                    it.setGateWayName(gateName);
                }
            });
        }
        return PageResult.success(page.getRecords(), page.getTotal());
    }

    /**
     * 构造查询条件
     *
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<CardAlarm> lambda, CardAlarmDTO param) {
        lambda.like(Objects.nonNull(param.getCardno()), CardAlarm::getCardno, param.getCardno());
        lambda.orderBy(true, false, CardAlarm::getId);
    }


}